import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import $config from './config.js'



const store = new Vuex.Store({
	state: {
		userInfo: uni.getStorageSync($config.__key_member) ?? {},
		apiToken: uni.getStorageSync($config.__key_token) ?? '',
		needRegister: uni.getStorageSync($config.__key_need_login) ?? true,
		registerType: uni.getStorageSync($config.__key_register_type) ?? '',
		zjxlAuthorStatus: false,
	},
	mutations: {
		// 登录成功
		login(state, res) {
			state.userInfo = res.userInfo;
			state.apiToken = res.apiToken;
			state.needRegister = res.needRegister;
			state.registerType = res.registerType;

			uni.setStorageSync($config.__key_member, state.userInfo);
			uni.setStorageSync($config.__key_token, state.apiToken);
			uni.setStorageSync($config.__key_need_login, state.needRegister);
			uni.setStorageSync($config.__key_register_type, state.registerType);
		},

		// 注销
		logout(state) {
			state.userInfo = {};
			state.apiToken = '';
			state.needRegister = true
			uni.removeStorage({
				key: $config.__key_member
			})
			uni.removeStorage({
				key: $config.__key_token
			})
			uni.removeStorage({
				key: $config.__key_need_login
			})
		},
		putState(state, payload) {

			let nameArr = payload.name.split('.');
			let saveKey = '';
			let len = nameArr.length;
			if (len >= 2) {
				let obj = state[nameArr[0]];
				for (let i = 1; i < len - 1; i++) {
					obj = obj[nameArr[i]];
				}
				obj[nameArr[len - 1]] = payload.value;
				saveKey = nameArr[0];
			} else {
				state[payload.name] = payload.value;
				saveKey = payload.name;
			}
			uni.setStorageSync(saveKey, state[saveKey])
		}
	}
})

export default store